var mongoose = require('mongoose');
const DataModel = require("../models/cate_model");


exports.create = function(req, res, next){
    const dataModel = new DataModel(req.body);
    // console.log(user)
    dataModel.save()
        .then(data=>{
            res.json(data);
        })
}

exports.get = function(req, res, next){
    var id = req.params.id;
    DataModel.findById(id, function (err, data) {
        res.json(data);
    })
}

exports.update = function(req, res, next){
    var id = req.params.id;
    DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})
        .then(data=>{
            //此时的返回值是修改之前的，而非修改之后的，所以可以去MongoDB中去查看修改以后的情况
            res.json(data);
        })
}
exports.remove = function(req, res, next){
    var id = req.params.id;
    DataModel.findByIdAndRemove(id, function(err,data){
        res.json(data);
    })
}
function reverseTree(data, pid){
    var result = [],
        temp;
    var data = JSON.parse(JSON.stringify(data));

    for (var i in data) {
        if(data[i].parentId == pid){
            result.push(data[i]);
            temp = reverseTree(data,data[i]._id);
            if(temp.length>0){
                data[i].children = temp;
            }
        }
    }
    return result;


}
exports.list = function(req, res, next){

    DataModel.find({},function(err, data){
        var allTree = reverseTree(data,);
        res.json(allTree);
    })
}

exports.listss = function(req, res, next){
    var oriId = req.body.id;
    var result = [];
    DataModel.findOne({_id:oriId},function(err, data){
        // console.log(data);
        result.push(oriId);
        data.getChildren(function(err, dataChildren){
            // console.log(dataChildren);
            for (var i in dataChildren) {
                // console.log(dataChildren[i]._id);
                result.push(dataChildren[i]._id);
            }
            res.json(result);
            // console.log(result);

        })
        // console.log(data);
    })
}

exports.deletes = function(req, res, next){
    // console.log(req.body.ids);
    var id = req.body.id;
    // console.log(id);
    var result = [];
    DataModel.findOne({_id:id},function(err, data){
        // console.log(data);
        result.push(id);
        data.getChildren(function(err, dataChildren){
            //dataChildren即为要删除节点的子节点
            // console.log(dataChildren);
            for (var i in dataChildren) {
                // console.log(dataChildren[i]._id);
                result.push(dataChildren[i]._id);
            }
            DataModel.remove({_id:{$in:result}})
                .then(dt=>{
                     res.json({"msg":'success',"status":200})
                })
        })
        // console.log(data);
    })
}


